import { defineStore } from 'pinia'
import type { UserState } from '../types/type'
import { setToken, getToken, removeToken } from '@/utils/token'
// 用户登录相关接口
import { reqLogin, reqUserInfo, reqLogout } from '@/api/user/index'
// 引入路由
import { constantRoute, asyncRoutes, anyRoute } from '@/router/routes'
// 定义接口和返回数据类型
import type {
  loginFormData,
  loginResponseData,
  userInfoResponseData,
} from '@/api/user/type'
import cloneDeep from 'lodash/cloneDeep'
// 筛选异步路由
import router from '@/router'
function filterAsyncRoutes(asyncRoutes: any, routes: any) {
  return asyncRoutes.filter((item: any) => {
    if (routes.includes(item.name)) {
      if (item.children && item.children.length) {
        item.children = filterAsyncRoutes(item.children, routes)
      }
      return true
    }
  })
}

// 定义user相关仓库
const useUserStore = defineStore('userStore', {
  state: (): UserState => {
    return {
      token: getToken(),
      menuRoutes: constantRoute,
      username: '',
      avatar: '',
      userButtonsPermission: [],
    }
  },
  actions: {
    // 登录
    async userLogin(data: loginFormData) {
      const res: loginResponseData = await reqLogin(data)
      if (res.code === 200) {
        this.token = res.data as string
        setToken(this.token)
        return 'ok'
      } else {
        return Promise.reject(new Error(res.data))
      }
    },
    // 获取用户信息
    async getUerInfo() {
      const res: userInfoResponseData = await reqUserInfo()
      if (res.code === 200) {
        this.username = res.data.name
        this.avatar = res.data.avatar
        // 存储按钮权限
        this.userButtonsPermission = res.data.buttons
        const userAsyncRoutes = filterAsyncRoutes(
          cloneDeep(asyncRoutes),
          res.data.routes,
        )
        const asyncRoutesAndAnyRoutes = [...userAsyncRoutes, anyRoute]
        asyncRoutesAndAnyRoutes.forEach((route) => {
          router.addRoute(route)
        })
        this.menuRoutes = [...constantRoute, ...asyncRoutesAndAnyRoutes]
        console.log(router.getRoutes())
        console.log('this.menuRoutes', this.menuRoutes)
        return 'ok'
      } else {
        return Promise.reject(new Error(res.data.message))
      }
    },
    // 退出登录
    async userLogout() {
      const res: any = await reqLogout()
      if (res.code === 200) {
        this.username = ''
        this.avatar = ''
        this.token = ''
        removeToken()
      } else {
        Promise.reject(new Error(res.message || 'default error'))
      }
    },
  },
})

export default useUserStore
